/* 

sendAjax({method = 'get',data = {}, url}) 发送ajax

Darg() 拖拽

BufferMove() 链式运动

SlideShow() 轮播图

getStyle() 获取计算后属性

ajax()  method : 'get',
        url : './1.txt',
        data : {
            name : 'aa',
            age : 18
        },
        success : function(e){
            console.log(e);
        }

random() 随机数

checkCode() 随机验证码

bindEvent(元素，事件，方法) 绑定事件

delEvent(元素，事件) 解除事件

stopBubble() 阻止冒泡

stopPrevent() 阻止默认

getOffset()  获取至视口距离offset值    参数： 元素、'top'或'left'

Magnifying()  放大镜

Slider(id) 拖动进度条

----------------分隔线--------------------

轮播图
SlideShow('banner')
<!-- banner -->
<div id="banner">
    <ul class="clearfix"></ul>
    <ol></ol>
    <a href="javascript:;" class="prev"></a>
    <a href="javascript:;" class="next"></a>
</div>


放大镜
<div id="box">
    <div class="mask"></div>
    <img src="./pic/1280x1024.png" alt="" class="littleImg">
    <div class="magnify">
        <img src="./pic/1280x1024.png" alt="" class="bigImg">
    </div>
</div>

拖动进度条
<div id="slider">
    <div class="plan"></div>
    <div class="slider_btn"></div>
</div>


*/

var store  = (function(){
    /* 
    拖拽 
        el --> 元素
    */
    function Darg(el){

        this.node = document.getElementById(el);

        this.offsetL = this.offsetT = 0;

        this.init();

    }

    Darg.prototype = {

        init : function(){

            var _this = this;

            this.node.onmousedown = function(){

                _this.down();
            };


        },

        down : function(e){

            var e = e || event;

            this.offsetL = e.offsetX;
            this.offsetT = e.offsetY;

            var _this = this;

            document.onmousemove = function(e){

                var e = e || event;

                _this.move(e);

            }

            document.onmouseup = this.up;

        },

        move : function(e){

            var e = e || event;

            var l = e.clientX  - this.offsetL;
            var t = e.clientY  - this.offsetT;

            if(l <= 0 ){
                l = 0;
            }

            if(l >= document.documentElement.clientWidth - this.node.offsetWidth){

                l = document.documentElement.clientWidth - this.node.offsetWidth;

            }

            if(t <= 0){
                t = 0;
            }

            if(t >= document.documentElement.clientHeight - this.node.clientHeight){
                t = document.documentElement.clientHeight - this.node.clientHeight;
            }

            this.node.style.left =l+ 'px';
            this.node.style.top = t + 'px';

        },

        up : function(){
            this.onmousemove = null;
            this.onmouseup = null;
        }

    }

    /* 
        获取计算属性
            元素 ， 属性
    */    
    function getStyle(ele,attr){
        return ele.currentStyle ? ele.currentStyle[attr] : getComputedStyle(ele)[attr];
    }

    /* 
        缓冲运动
            元素，属性值obj ，回调函数
    */

    function BufferMove(el,obj,cb){

        this.el = el;

        this.obj = obj;

        this.cb = cb;

        this.flag = true;

        this.init();

    }

    BufferMove.prototype.init = function(){

        clearInterval(this.el.timer);

        var _this = this;

        this.el.timer = setInterval(function(){
            _this.move();
        },20)

    }

    BufferMove.prototype.move = function(){

        this.flag = true;
        
        for(var key in this.obj){

            if(key == 'opacity'){
                var cur = Math.round(getStyle(this.el,key) * 100)
            }else{
                var cur = parseInt(getStyle(this.el,key))
            }

            var step = (this.obj[key] - cur) / 10;

            step = step > 0 ? Math.ceil(step) : Math.floor(step);

            if(this.obj[key] != cur){
                this.flag = false;
            }

            if(key == 'opacity'){
                this.el.style[key] = (cur + step) / 100;
            }else{
                this.el.style[key] = cur + step + 'px';
            }

        }

        if(this.flag){
            
            clearInterval(this.el.timer);

            if(this.cb) this.cb.call(this.el);
        }
    }

    /* 
        轮播图
            el ---> 元素
    */

    function SlideShow(el){

        this.box = document.getElementById(el);
        
        this.prev = this.box.getElementsByTagName('a')[0];
        this.next = this.box.getElementsByTagName('a')[1];
        
        this.ul = this.box.getElementsByTagName('ul')[0]; // img 父盒子
        this.ol = this.box.getElementsByTagName('ol')[0]; // 圆点 父盒子
        
        this.scrollWidth = this.ul.offsetWidth; // 滚动距离
        this.len = this.ul.children.length; // 图片数量
        this.imgs = this.ul.children;// 所有图片
        this.num = 0; // 记录当前播放的索引
        this.timer = null; // 定时器
        this.lis = null; // 所有圆点
        this.now = null; // 记录当前显示的图片

        this.init();

    }

    SlideShow.prototype.init = function(){

        var _this = this;

        this.create();
        
        this.next.onclick = function(){
            _this.nextPic();
        }

        this.prev.onclick = function(){
            _this.prevPic();
        }

        this.ol.onclick = function(){

            _this.liClick();
        }

        this.autoPaly();

    }

    // 创建圆
    SlideShow.prototype.create = function(){
        // 创建图片同数量个圆
        for(var i = 0; i < this.len; i++){
            
            var li = document.createElement('li');

            li.index = i;  // 圆点的索引

            this.imgs[i].index = i; // img索引

            this.ol.appendChild(li);
            
            // 所有图片都移动到可视区右边
            this.ul.children[i].style.left = this.scrollWidth + 'px';
        }
        // 第一张图片 0 ，第一个圆点加样式
        this.ul.children[0].style.left = 0;
        this.ul.children[0].style.zIndex = 2;

        this.ol.children[0].className = 'current';

        this.lis = this.ol.children; // 所有圆点
    }

    // 下一张
    SlideShow.prototype.nextPic = function(){

        this.now = this.imgs[this.num]; // 记录当前显示的图片

        this.num++;

        if(this.num == this.len) this.num = 0;
        
        this.animation(this.now,this.num);
    }

    // 播放
    SlideShow.prototype.animation = function(){

        this.imgs[this.num].style.zIndex = Number(this.now.style.zIndex) + 1; // 要进来的图片层级 比当前的层级+1

        if(this.num > this.now.index ){

            this.imgs[this.num].style.left = this.scrollWidth + 'px'; // 要进来的图片移到右边
        }else{

            this.imgs[this.num].style.left = -this.scrollWidth + 'px'; // 要进来的图片移到左边
        }

        // 第一张到最后
        if(this.now.index == 0 && this.num == this.len-1){
            this.imgs[this.num].style.left = -this.scrollWidth + 'px'; // 要进来的图片移到右边
        }

        // 最后到第一张
        if(this.now.index == this.len-1 && this.num == 0){
            this.imgs[this.num].style.left = this.scrollWidth + 'px'; // 要进来的图片移到左边
        }

        // 开始移动
        new BufferMove(this.imgs[this.num],{left : 0})
        // 刷新圆点
        this.resLi(this.num);
    }

    // 刷新圆点
    SlideShow.prototype.resLi = function(index){

        for(var i = 0; i < this.lis.length; i++){

            this.lis[i].className = '';
        }

        this.lis[index].className = 'current';
    }

    // 上一张
    SlideShow.prototype.prevPic= function (){

        this.now = this.imgs[this.num]; // 记录当前显示的图片

        this.num--;

        if(this.num < 0) this.num = this.len - 1;

        this.animation(this.now,this.num);

    }

    // 点击小圆点
    SlideShow.prototype.liClick = function(e){

        var e = e || event;

        var target = e.target || e.srcElement;

        if(target.nodeName.toLowerCase() == 'li'){

            if(target.index == this.num) return;

            this.now = this.imgs[this.num]; // 记录当前显示的图片

            this.num = target.index; // 点击的下标 赋值给 记录当前的num

            this.animation(this.now,this.num);
            
        }
    }

    // 自动播放
    SlideShow.prototype.autoPaly = function(){

        var _this = this;

        _this.timer = setInterval(function(){

            _this.nextPic();
        
        },3000)
        
        _this.box.onmouseenter = function(){
        
            clearInterval(_this.timer);

            _this.box.onmouseleave = function(){
        
                _this.timer = setInterval(function(){
            
                    _this.nextPic();
            
                },3000)
    
            }

        }
        
        
    }

    /* 
    {
        method : 'get',
        url : './1.txt',
        data : {
            name : 'aa',
            age : 18
        },
        success : function(e){
            console.log(e);
        }
    }
    */
    function ajax(setting){

        var ajax = new XMLHttpRequest();

        // 默认 set
        if(!setting.method) setting.method = 'get';

        // 组合data查询数据
        if(setting.data){

            setting.data = querySearch(setting.data);

        }else{

            setting.data = '';

        } 


        if(setting.method.toLowerCase() == 'get'){

            ajax.open('get',setting.url + '?' + setting.data,true);

            ajax.send();

        }else if(setting.method.toLowerCase() == 'post'){

            ajax.open('post',setting.url,true);

            ajax.setRequestHeader('Content-type','appliction/x-www-form-urlencoded');

            ajax.send(setting.data);

        }

        ajax.onreadystatechange = function(){

            if(ajax.readyState == 4){

                if(ajax.status == 200){

                    setting.success(ajax.responseText);

                }else{
                    console.log('Error:' + ajax.status);
                }

            }
        }
    }

    // 拼接字符串
    function querySearch(obj){
        var str = '';
        for(var key in obj){
            str += key + '=' + obj[key] + '&';
        }
        return str.slice(0,str.length-1);
    }

    /* 
        随机数
        区间 n - m
    */
    function random(n,m){
        return Math.floor(Math.random() * (m - n + 1) + n);
    }

    /* 随机验证码 */
    function checkCode(n){
        var str = 'qwerasdfzxcvtyuiopghjklbnmQAZWSXEDCRFVTGBNHYMJUKILOP1209384756';
        var temp = '';
        for(var i = 0; i < n; i++){
            temp += str[Math.floor(Math.random() * (str.length - 1))];
        }
        return temp;
    }

    /* 绑定事件 */
    function bindEvent(el,event,fn){
        el.addEventListener ? el.addEventListener(event,fn,false) : el.attachEvent('on' + event,fn);
    }
    /* 解除事件 */
    function delEvent(el,event,fn){
        el.removeEventListener ? el.removeEventListener(event,fn) : el.detachEvent('on' + event,fn);
    }
    /* 阻止冒泡 */
    function stopBubble(e){

        var e = e || event;

        e.stopPropagation ? e.stopPropagation() : e.cancalBubble = true;
    }
    /* 阻止默认行为 */
    function stopPrevent(e){
        
        var e = e || event;

        e.preventDefault ? e.preventDefault() : e.returnValue = false;
    }
    /* 
        获取至视口距离offset值
        参数： 元素、'top'或'left'
    */
    function getOffset(el,sen){

        sen = sen[0].toUpperCase() + sen.slice(1);

        var num = 0;

        while(el.offsetParent){

            // num += el['offset' + sen];
            num += el['offsetLeft'];

            el = el.offsetParent;

        }
        return num;
    }
    /* 
        放大镜
        参数：id名
     */
    function Magnifying(el){

        this.box = document.getElementById(el);

        this.mask = this.box.querySelector('.mask');

        this.magnify = this.box.querySelector('.magnify');
        
        this.bigImg = this.box.querySelector('.bigImg');

        this.l = 0; // mask Left值 
        this.t = 0; // mask Top值

        this.init();
    }

    Magnifying.prototype = {

        init : function(){

            var _this = this;

            this.box.onmouseenter = function(){
                _this.enter();
            };

            this.box.onmouseleave = function(){
                _this.leave();
            };

        },

        enter : function(){

            var _this = this;

            this.mask.style.display = 'block';

            this.magnify.style.display = 'block';

            this.box.onmousemove = function(e){
                var e = e || event;
                _this.move(e);
            };
        },
        move : function(e){

            var e = e || event;

            this.l = e.clientX - this.mask.offsetWidth / 2 - getOffset(this.box,'left');
            this.t = e.clientY - this.mask.offsetHeight / 2 - getOffset(this.box,'top');

            this.maxL = this.box.offsetWidth - this.mask.offsetWidth;
            this.maxT = this.box.offsetHeight - this.mask.offsetHeight;

            if(this.l <= 0) this.l = 0;
            if(this.t <= 0) this.t = 0;

            if(this.l >= this.maxL){
                this.l = this.maxL;
            }

            if(this.t >= this.maxT){
                this.t = this.maxT;
            }

            this.mask.style.left = this.l + 'px';
            this.mask.style.top = this.t + 'px';

            this.scaleL = this.mask.offsetLeft / this.maxL;
            this.scaleT = this.mask.offsetTop / this.maxT;

            this.bigImg.style.top = -this.scaleT * (this.bigImg.offsetHeight - this.magnify.offsetHeight) + 'px';
            this.bigImg.style.left = -this.scaleL * (this.bigImg.offsetWidth - this.magnify.offsetWidth) + 'px';


        },
        leave : function(){
            
            this.mask.style.display = 'none';

            this.magnify.style.display = 'none';

        }
    }

    /* 
        Slider(id) 拖动进度条
     */
    function Slider(el){

        this.slider = document.getElementById(el);
        
        this.plan = this.slider.querySelector('.plan');
        
        this.slider_btn = this.slider.querySelector('.slider_btn');

        this.disX = 0;

        this.offX = 0;

        this.l = 0;

        this.init();
    }

    Slider.prototype = {

        init(){

            var _this = this;

            this.slider_btn.onmousedown = function(){
                
                _this.down();

                return false;

            }

            
        },

        down(){

            var e = e || event;

            var _this = this;

            this.disX = getOffset(this.slider,'left');
            // this.disX = this.slider.offsetLeft;

            this.offX = e.offsetX;

            document.onmousemove = function(e){

                var e = e || event;

                _this.move(e);
            }
            
            document.onmouseup = function(){
                
                this.onmousemove = null;

                this.onmouseup = null;
            }
            
        },

        move(e){

            var e = e || event;

            this.l = e.clientX - this.disX - this.offX;

            if(this.l <= 0) this.l = 0;

            if(this.l >= this.slider.offsetWidth - this.slider_btn.offsetWidth)
            this.l = this.slider.offsetWidth - this.slider_btn.offsetWidth;


            this.slider_btn.style.left = this.l + 'px';

            this.plan.style.width = this.slider_btn.offsetLeft + 'px';
        }

    }
    // 数字双数 
    function doubleNum(n){
        return n <= 9 ? '0' + n : n;
    }

    // 发送ajax
    function sendAjax({method = 'get',data = {}, url}){

        return new Promise((resolve,reject) => {
            store.ajax({ url, data,
                success(d){
                    d = JSON.parse(d);
                    resolve(d);
                },
                error(e){
                    reject(e);
                }
            })
        })
        
    }

    return {
        Darg : Darg,
        getStyle : getStyle,
        BufferMove : BufferMove,
        SlideShow : SlideShow,
        ajax : ajax,
        random :random,
        checkCode : checkCode,
        bindEvent : bindEvent,
        stopBubble : stopBubble,
        stopPrevent : stopPrevent,
        delEvent : delEvent,
        getOffset : getOffset,
        Magnifying : Magnifying,
        Slider : Slider,
        doubleNum : doubleNum,
        sendAjax : sendAjax,

    }

})()